<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大块中拖拽小块</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    
    .box {
        width: 400px;
        height: 400px;
        border: 10px solid #000;
        position: relative;
        margin: 20px auto;
    }
    
    .move {
        width: 150px;
        height: 100px;
        background: red;
        border: 5px solid rgb(0, 255, 0);
        position: absolute;
        cursor: move;
    }
</style>

<body>
    <div class="box">
        <div class="move"></div>
    </div>
    <script>
        var oBox = document.querySelector('.box');
        var oMove = document.querySelector('.move');
        var w = oBox.clientWidth - oMove.offsetWidth;
        var h = oBox.clientHeight - oMove.offsetHeight;
        console.log(w);
        oMove.onmousedown = function(e) {
            var ev = e || event;
            //求不变距离之和（紫色1）
            var disX = ev.clientX - oMove.offsetLeft;
            var disY = ev.clientY - oMove.offsetTop;
            document.onmousemove = function(e) {
                var ev = e || event;
                // 移动过程中拿鼠标坐标减去不变的距离即可求出 left 和 top 值
                var l = ev.clientX - disX;
                l = l < 0 ? 0 : (l > w ? w : l);
                var t = ev.clientY - disY;
                t = t < 0 ? 0 : (t > h ? h : t);

                oMove.style.left = l + 'px';
                oMove.style.top = t + 'px';
            }
            document.onmouseup = function() {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
    </script>
</body>

</html>